package demo2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-08-08
 * Time: 10:22
 */
public class EchoServer2 {
    private DatagramSocket echoServer2 = null;

    public  EchoServer2(int port) throws SocketException {
        echoServer2 = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器起动");
        while (true){

            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            echoServer2.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress());
            echoServer2.send(responsePacket);
            System.out.printf("[%s: %d] req: %s, res: %s\n", requestPacket.getAddress().toString(), requestPacket.getPort(),
                    request, response);

        }
    }

    private String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        EchoServer2 echoServer2 = new EchoServer2(9090);
        echoServer2.start();
    }

}
